package com.example.zpp_sdzx

import io.flutter.embedding.android.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.EventChannel
import android.telephony.SmsManager
import android.os.Build  // 添加这行导入

import android.os.Environment
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.BatteryManager
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.net.Uri
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import android.widget.Toast
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import androidx.annotation.NonNull;

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.zpp.sdzx_manage/file"
    private val GET_NAME_CHANNEL = "com.zpp.sdzx_manage/getName"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);


        EventChannel(flutterEngine.dartExecutor.binaryMessenger, GET_NAME_CHANNEL).setStreamHandler(object : EventChannel.StreamHandler {
            override fun onListen(p0: Any?, events: EventChannel.EventSink) {

                var locationListener=onLocation(events)
                var locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 3.0F, locationListener)
                //  locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000,0F, locationListener)
            }
            override fun onCancel(p0: Any?) {

            }
        })


        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
            // Note: this method is invoked on the main thread.
                call, result ->


            when {

                call.method == "getFileDir" -> {
                    result.success(getFileDir());
                }

                
                call.method == "sendCast" -> {
                    val path = call.arguments as String
                    result.success(sendCast(path))
                }

                call.method == "showToast" -> {
                    val path = call.arguments as String
                    result.success(showToast(path))
                }

                call.method == "saveFileToGallery" -> {
                    val path = call.arguments as String
                    result.success(saveFileToGallery(path))
                }

                call.method == "getLocation" -> {

                    result.success(getLocation(applicationContext))
                }

                call.method == "sendSMS" -> {
                    try {
                        val args = call.arguments as Map<*, *>
                        val phoneNumber = args["phone"] as String
                        val message = args["message"] as String
                        sendSMS(phoneNumber, message)
                        result.success(true)
                    } catch (e: Exception) {
                        result.error("SMS_ERROR", e.message, null)
                    }
                }

                else -> result.notImplemented()
            }
        }
    }


    private fun showToast(content: String): String{

        Toast.makeText(this,content, Toast.LENGTH_LONG).show()
        return ""
    }

    private fun sendSMS(phone: String, message: String) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val smsManager = context.getSystemService(SmsManager::class.java)
            smsManager.sendTextMessage(phone, null, message, null, null)
        } else {
            SmsManager.getDefault().sendTextMessage(phone, null, message, null, null)
        }
    }

    private fun sendSMS2(phoneNumber: String, message: String) {
        val smsManager = SmsManager.getDefault()
        smsManager.sendTextMessage(phoneNumber, null, message, null, null)
    }


    private fun sendCast(filePath: String): String{


        return try {
            var file = File(filePath);
            val uri = Uri.fromFile(file)
            applicationContext.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
            return uri.toString()
        } catch (e: IOException) {
            e.printStackTrace()
            ""
        }

    }

    private fun generateFile(filename: String = ""): File {
        val storePath =  Environment.getExternalStorageDirectory().absolutePath + File.separator +"水调中心"
        val appDir = File(storePath)
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        var f1=File(appDir, filename)
        if (!f1.exists()) {
            return f1;
        }
        var filename2  = System.currentTimeMillis().toString()+filename
        return File(appDir, filename2)
    }


    private fun getFileDir(): String {
        val storePath =  Environment.getExternalStorageDirectory().absolutePath + File.separator + "水调中心"
        val appDir = File(storePath)
        if (!appDir.exists()) {
            appDir.mkdir()
        }

        return appDir.path
    }

    private fun saveFileToGallery(filePath: String): String {

        return try {
            val originalFile = File(filePath)
            val file = generateFile(originalFile.getName())
            originalFile.copyTo(file)

            val uri = Uri.fromFile(file)
            applicationContext.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
            return uri.toString()
        } catch (e: IOException) {
            e.printStackTrace()
            ""
        }
    }


    private fun getBatteryLevel(): Int {
        val batteryLevel: Int
        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
            batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
        } else {
            val intent = ContextWrapper(applicationContext).registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
            batteryLevel = intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
        }

        return batteryLevel
    }



    //获取位置
    private fun getLocation(context: Context): String {
        val locMan = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        var location: Location? = null


        locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 3.0F, onLocation2)
        location = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER)
        if (location == null) {

            location = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
        }

        var xx="定位错误"
        if(location!=null){
            xx = "" + location.getLatitude() + ","+ location.getLongitude()
        }

        return xx
    }



    //持续定位
    private fun onLocation(events: EventChannel.EventSink):LocationListener {
        return object : LocationListener {
            override fun onProviderDisabled(provider: String) {
                events.success("关闭了GPS")
            }

            override fun onProviderEnabled(provider: String) {
                events.success("打开了GPS")
            }

            override fun onLocationChanged(location: Location) {
                var xx="定位错误"
                if(location!=null){
                    xx = "" + location.getLatitude() + ","+ location.getLongitude()
                }
                events.success( xx)

            }

            override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
                events.success("onStatusChanged")

            }
        }
    }

    private val onLocation2: LocationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            //  thetext.text = ("" + location.longitude + ":" + location.latitude)
        }
        override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
        override fun onProviderEnabled(provider: String) {}
        override fun onProviderDisabled(provider: String) {}
    }

    // private val onLocation2=LocationListener {
    //     return object : LocationListener {
    //         override fun onProviderDisabled(provider: String?) {

    //         }

    //         override fun onProviderEnabled(provider: String?) {

    //         }

    //         override fun onLocationChanged(location: Location?) {
    //         }

    //         override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {

    //         }
    //     }
    // }


}
